package megalopolis.client;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;

import megalopolis.common.ManagableThread;
import megalopolis.net.Request;
import megalopolis.net.Response;

/**
 * User: Kirill
 * Date: 19.02.2008
 */
public class NetworkHandler extends ManagableThread {

	private ObjectInputStream in;

	private ObjectOutputStream out;

	private ResponseHandler responseHandler;

	public NetworkHandler(Socket socket, ResponseHandler responseHandler) {
		super(0);
		this.responseHandler = responseHandler;
		try {
			in = new ObjectInputStream(socket.getInputStream());
			out = new ObjectOutputStream(socket.getOutputStream());
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public void threadStep() {
		try {
			Response resp = (Response) in.readObject();
			responseHandler.handleResponse(resp);
		} catch (IOException e) {
			e.printStackTrace();
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}
	}

	public void sendRequest(Request request) {
		try {
			out.reset();
			out.writeObject(request);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public Response sendSyncRequest(Request request) {
		try {
			out.writeObject(request);

			Response resp;
			do {
				resp = (Response) in.readObject();
			} while (resp == null);

			return resp;
		} catch (IOException e) {
			e.printStackTrace();
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}

		return null;
	}

}
